<?php

class PlayerMapper
{
	private function __construct() {}
	private function __destruct() {}
	private function __clone() {}
	
	public static function insert(PlayerObject $player)
	{
		$query = sprintf("INSERT INTO `players` (`name`, `password`, `mail`, `ac_level`, `gold`, `about`, `register_date`) VALUES ('%s', '%s', '%s', %d, %f, '%s', %d);",
				DataBase::i()->escape($player->name()), $player->password(), $player->mail(),
				$player->acLevel(), $player->gold(), DataBase::i()->escape($player->about()), $player->registerDate());
		$res = DataBase::i()->query($query);
		if ($res === false)
			return false;
		
		$player->setId(DataBase::i()->insertId());
		
		return true;
	}
	
	public static function update(PlayerObject $player)
	{
		$query = sprintf("UPDATE `players` SET `name` = '%s', `mail` = '%s', `password` = '%s', `about` = '%s', `gold` = %f, `ac_level` = %d WHERE `id` = %d ",
				DataBase::i()->escape($player->name()), $player->mail(), $player->password(),
				DataBase::i()->escape($player->about()), $player->gold(), $player->acLevel(), $player->id());
	
		$res = DataBase::i()->query($query);
		if ($res === false)
			return false;
	
		$player->saved();
		return true;
	}
	
	public static function byName($name)
	{
		$query = sprintf("SELECT * FROM `players` WHERE UPPER(`name`) = UPPER('%s') LIMIT 1", DataBase::i()->escape($name));
		$res = DataBase::i()->query($query);
		if ($res->rows() == 0)
			return null;
		return new PlayerObject($res->fetch());
	}
	
	public static function byMail($mail)
	{
		$query = sprintf("SELECT * FROM `players` WHERE UPPER(`mail`) = UPPER('%s') LIMIT 1", DataBase::i()->escape($mail));
		$res = DataBase::i()->query($query);
		if ($res->rows() == 0)
			return null;
		return new PlayerObject($res->fetch());
	}
	
	public static function byId($id)
	{
		settype($id, "int");
		$query = sprintf("SELECT * FROM `players` WHERE `id` = %d LIMIT 1", $id);
		$res = DataBase::i()->query($query);
		if ($res->rows() == 0)
			return null;
		return new PlayerObject($res->fetch());
	}
	
	public static function playersId()
	{
		$query = "SELECT `id` FROM `players`";
		$res = DataBase::i()->query($query);
		
		$players = array();
		while (($row = $res->fetch()))
			$players[] = $row["id"];
		return $players;
	}
	
	public static function delete($id)
	{
		if (is_object($id))
			$id = $id->id();
		$query = sprintf("DELETE FROM `players` WHERE `id` = %d LIMIT 1", $id);
		DataBase::i()->query($query);
	}
}

?>